import re
from users.models import User
from django.contrib.auth.backends import ModelBackend


# 当你采用了JWT认证登陆，登陆过后就会调用此方法，把认证的用户登陆信息传递过来了
# 所以只要登陆过后user就不是None了

def jwt_response_payload_handler(token, user=None, request=None):
    return {
        'token': token,
        'username': user.username,
        'user_id':user.id
    }

# 增加支持用户名与手机号均可作为登录账号
# 1.修改Django认证系统的认证后端需要继承django.contrib.auth.backends.ModelBackend，并重写authenticate方法

def get_user_by_account(account):
    try:

        if re.match(r"1[3456789]\d{9}",account):
            user = User.objects.get(mobile=account)

        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        user = None

    return user


class UsernameMobleAuth(ModelBackend):
#     重写authenticate方法添加用户手机号认证等登陆
#     username=None,password=None 就是在登陆的时候输入的
    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_by_account(username)

        if user is not None and user.check_password(password):

            return user

        return None

class SettingsBackend(object):

    def authenticate(self, request, username=None, password=None):
        user = get_user_by_account(username)

        if user is not None and user.check_password(password):
            return user

        return None

    # 继承自object的类需要多实现一个get_user方法
    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None
